package leetcode.code0391;

import java.util.HashSet;
import java.util.Set;

public class Solution extends Solution391 {

	@Override
	public boolean isRectangleCover(int[][] rectangles) {
		Set<String> set = new HashSet<>();
		int area = 0;
		for (int[] rect : rectangles) {
			area += this.area(rect);
			String pos = null;
			if (set.contains((pos = this.posa(rect)))) {
				set.remove(pos);
			} else {
				set.add(pos);
			}
			if (set.contains((pos = this.posb(rect)))) {
				set.remove(pos);
			} else {
				set.add(pos);
			}
			if (set.contains((pos = this.posc(rect)))) {
				set.remove(pos);
			} else {
				set.add(pos);
			}
			if (set.contains((pos = this.posd(rect)))) {
				set.remove(pos);
			} else {
				set.add(pos);
			}
		}
		if (set.size() != 4)
			return false;
		int total = this.total(set);
		return total == area;
	}

	private int total(Set<String> set) {
		Integer a = null;
		Integer b = null;
		int c = 0;
		int d = 0;
		int w = 0;
		int h = 0;
		for (String pos : set) {
			String[] p = pos.split("_");
			if (a == null) {
				a = Integer.valueOf(p[0]);
				b = Integer.valueOf(p[1]);
			} else {
				c = Integer.valueOf(p[0]);
				d = Integer.valueOf(p[1]);
				if (a == c) {
					h = Math.abs(d - b);
				}
				if (b == d) {
					w = Math.abs(c - a);
				}
			}
		}
		return w * h;
	}

	// 面积
	private int area(int[] rest) {
		return this.getHeigth(rest) * this.getWidth(rest);
	}

	// 矩形高度
	private int getHeigth(int[] rest) {
		return rest[3] - rest[1];
	}

	// 宽度
	private int getWidth(int[] rest) {
		return rest[2] - rest[0];
	}

	// D B
	// A C
	private String posc(int[] rest) {
		return rest[2] + "_" + rest[1];
	}

	private String posd(int[] rest) {
		return rest[0] + "_" + rest[3];
	}

	private String posa(int[] rest) {
		return rest[0] + "_" + rest[1];
	}

	private String posb(int[] rest) {
		return rest[2] + "_" + rest[3];
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug5();
//		so.debug1();
//		so.debug2();
//		so.debug3();
//		so.debug4();
	}

}
